package com.liujie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liujie.dto.DishDto;
import com.liujie.entity.Dish;
import com.liujie.entity.DishFlavor;
import com.liujie.mapper.DishMapper;
import com.liujie.service.CategoryService;
import com.liujie.service.DishFlavorService;
import com.liujie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    @Override
    public boolean saveWithFlavor(DishDto dishDto) {
        boolean save = this.save(dishDto);
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }
        boolean b = dishFlavorService.saveBatch(flavors);
        if (save && b){
            return true;
        }
        return false;
    }

    @Override
    public DishDto getOneWithFlavor(long id) {
        DishDto dishDto=new DishDto();
        Dish dish = this.getById(id);
        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(lqw);

        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setCategoryName(categoryService.getById(dish.getCategoryId()).getName());
        dishDto.setFlavors(dishFlavors);

        return dishDto;
    }

    @Override
    public boolean updateWithFlavor(DishDto dishDto) {
        boolean b1 = this.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        boolean b2 = dishFlavorService.remove(lqw);//删除之前的口味
        List<DishFlavor> flavors = dishDto.getFlavors();//现在的口味
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        boolean b3 = dishFlavorService.saveBatch(flavors);//添加现在的口味

        if (b1 && b2 && b3){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteWithFlavor(long ids) {
        boolean b = this.removeById(ids);
        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,ids);
        boolean remove = dishFlavorService.remove(lqw);
        if (b && remove){
            return true;
        }
        return false;
    }
}
